#!/usr/bin/env python
#coding:utf-8  

from web.contrib.template import render_mako
render = render_mako(
           directories=['templates'],
           input_encoding='utf-8',
           output_encoding='utf-8',
           )  


fliter_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"
fliter_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"
fliter_html = "<[^>]+>"
fliter_words = "法轮功|共产党"

def fliteText(text):
    global fliter_script,fliter_style,fliter_html,fliter_words
    result = re.sub(fliter_words, "*", text)
    result = re.sub(fliter_script, "", result)
    result = re.sub(fliter_style, "", result)
    result = re.sub(fliter_html, "", result)
    return result  


#print fliteText("我是共产党和法轮功")

def getUUID():
    return str(uuid.uuid1()).replace('-','')       



def getVcodeImage():
    import Image, ImageDraw, ImageFont, md5, datetime,cStringIO
    data = cStringIO.StringIO()
    draw = None
    cdata = None
    ctext = None
    try:
        bgcolor = (218,243,203) 
        fontcolor = (32,74,12) 
        linecolor = (92,185,30) 
        im = Image.new("RGB",(80,30),bgcolor) 
        font = ImageFont.truetype("vcode.ttf", 24) 
        #font = ImageFont.truetype("/usr/share/fonts/chinese/TrueType/ukai.ttf", 24)     
        #font = ImageFont.load_default()
        #print dir(font)
        draw = ImageDraw.Draw(im)   
        mp = md5.new()   
        mp_src = mp.update(str(datetime.datetime.now()))   
        mp_src = mp.hexdigest()   
        ctext = mp_src[0:6]       
        draw.text((5,2), ctext,font=font,fill=fontcolor)   
        draw.line([(0,0),(0,29)],linecolor)
        draw.line([(0,29),(79,29)],linecolor)
        draw.line([(79,0),(79,29)],linecolor)
        draw.line([(0,0),(79,0)],linecolor)
        im.save(data,"JPEG") 
        cdata = data.getvalue()
    except Exception,e:
        import traceback
        print e
        traceback.print_exc()
    finally:
        del draw   
        if data:data.close()
    return cdata,ctext   

def formatCtime(ctime):
    if not ctime: return
    ftime = time.strptime( ctime, '%Y-%m-%d %H:%M:%S' )
    curtime = time.localtime()
    
    ms = time.mktime( curtime ) - time.mktime( ftime )
    mms = round(ms/60);
    hhs = round(mms/60);
    dds = round(hhs/24);
    if dds>0: return u'%d天前'%(dds);
    if hhs>0: return u'%d小时前'%(hhs);
    if mms>0: return u'%d分钟前'%(mms);
    return u"刚才";       
